//
//  URL+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 2019/7/17.
//  Copyright © 2019 PPKit. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import Foundation

let KUrlCodingReservedCharacters = "!*'();:|@&=+$,/?%#[]{}"

extension URL{
    
    /// 根据参数名获取URL参数值
    ///
    /// - Parameter name: <#name description#>
    /// - Returns: <#return value description#>
    func valueForQueryName(name:String) -> String? {
        var retValue:String?
        
        if let querys = self.query?.components(separatedBy: "&") {
            for query in querys{
                let params = query.components(separatedBy: "=")
                if params[0] == name {
                    retValue = params[1].urlEncode()
                    break
                }
            }
        }
        return retValue
    }
}

extension String{
    //MARK: URL编码解码
    //将原始的url编码为合法的url
    func urlEncode() -> String? {
        //return self.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: KUrlCodingReservedCharacters).inverted)
        return self.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)
    }
    
    /// URL解码
    /// - Returns: <#description#>
    func urlDecode() -> String? {
        return self.removingPercentEncoding
    }
}
